package anatex.kea.stemmers;

import java.io.*;
// jdk 1.4+!!!
import java.util.regex.*;
import java.util.*;

import anatex.domain.StemmerRules;

/**
 * Stemming algorithm by Preslav Nakov.
 * @author Alexander Alexandrov, e-mail: sencko@mail.bg
 * @since 2003-9-30
 */
public class BulgarianStemmer extends Stemmer {
  
  public Hashtable stemmingRules = new Hashtable();
  
  public int STEM_BOUNDARY = 1;

  public static Pattern vocals = Pattern.compile("[^аъоуеияю]*[аъоуеияю]");
  public static Pattern p = Pattern.compile("([а-я]+)\\s==>\\s([а-я]+)\\s([0-9]+)");
  
  public BulgarianStemmer() {
	  try {
		  loadStemmingRules("WEB-INF/stem_rules_context_2.txt");
	  } catch(Exception ex) {
		  ex.printStackTrace(System.out);
	  }
  }
  
  public void loadStemmingRules(String fileName) throws Exception {
    stemmingRules.clear();
    String str = StemmerRules.findStemmerRules(1l).getStemmerRules();
    
    BufferedReader br = new BufferedReader(new StringReader(str));
    String s = null;
    while ((s = br.readLine()) != null) {
      Matcher m = p.matcher(s);
      if (m.matches()) {
        int j = m.groupCount();
        if (j == 3) {
          if (Integer.parseInt(m.group(3)) > STEM_BOUNDARY) {
            stemmingRules.put(m.group(1), m.group(2));
          }
        }
      }
    }
  }

  public String stem(String str) {
    Matcher m = vocals.matcher(str);
    if (!m.lookingAt()) {
      return str;
    }
    for (int i = m.end() + 1; i < str.length(); i++) {
      String suffix = str.substring(i);
      if ((suffix = (String) stemmingRules.get(suffix)) != null) {
        return str.substring(0, i) + suffix;
      }
    }
    return str;
  }
  
}